{% extends 'base.html' %}
{% load static %}

{% block title %}我的卡牌收藏{% endblock %}

{% block content %}
<style>
/* 覆盖base.html的container限制 */
main.container {
    max-width: none !important;
    padding: 0 !important;
}
</style>
<div class="container-fluid" style="margin-top: 1rem;">
    <div class="row">
        <!-- 左侧筛选面板 -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-header">
                    <h5><i class="fas fa-filter"></i> 筛选条件</h5>
                </div>
                <div class="card-body">
                    <!-- 显示模式 -->
                    <div class="mb-3">
                        <label class="form-label">显示模式</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="showAllCards" onchange="toggleShowAll()">
                            <label class="form-check-label" for="showAllCards">
                                显示全部卡牌（包括未拥有）
                            </label>
                        </div>
                    </div>

                    <!-- 搜索框 -->
                    <div class="mb-3">
                        <label for="searchInput" class="form-label">搜索卡牌</label>
                        <input type="text" class="form-control" id="searchInput" placeholder="输入卡牌名称..." onkeyup="filterCards()">
                    </div>

                    <!-- 星级筛选 -->
                    <div class="mb-3">
                        <label class="form-label">星级</label>
                        <div class="btn-group-vertical w-100" role="group">
                            <input type="radio" class="btn-check" name="starFilter" id="starAll" value="" checked onchange="filterCards()">
                            <label class="btn btn-outline-primary" for="starAll">全部</label>
                            
                            <input type="radio" class="btn-check" name="starFilter" id="star1" value="1" onchange="filterCards()">
                            <label class="btn btn-outline-primary" for="star1">1星</label>
                            
                            <input type="radio" class="btn-check" name="starFilter" id="star2" value="2" onchange="filterCards()">
                            <label class="btn btn-outline-primary" for="star2">2星</label>
                            
                            <input type="radio" class="btn-check" name="starFilter" id="star3" value="3" onchange="filterCards()">
                            <label class="btn btn-outline-primary" for="star3">3星</label>
                            
                            <input type="radio" class="btn-check" name="starFilter" id="star4" value="4" onchange="filterCards()">
                            <label class="btn btn-outline-primary" for="star4">4星</label>
                            
                            <input type="radio" class="btn-check" name="starFilter" id="star5" value="5" onchange="filterCards()">
                            <label class="btn btn-outline-primary" for="star5">5星</label>
                        </div>
                    </div>

                    <!-- 属性筛选 -->
                    <div class="mb-3">
                        <label class="form-label">属性</label>
                        <div class="btn-group-vertical w-100" role="group">
                            <input type="radio" class="btn-check" name="elementFilter" id="elementAll" value="" checked onchange="filterCards()">
                            <label class="btn btn-outline-primary" for="elementAll">全部</label>
                            
                            <input type="radio" class="btn-check" name="elementFilter" id="elementMetal" value="metal" onchange="filterCards()">
                            <label class="btn btn-outline-warning" for="elementMetal">金</label>
                            
                            <input type="radio" class="btn-check" name="elementFilter" id="elementWood" value="wood" onchange="filterCards()">
                            <label class="btn btn-outline-success" for="elementWood">木</label>
                            
                            <input type="radio" class="btn-check" name="elementFilter" id="elementWater" value="water" onchange="filterCards()">
                            <label class="btn btn-outline-info" for="elementWater">水</label>
                            
                            <input type="radio" class="btn-check" name="elementFilter" id="elementFire" value="fire" onchange="filterCards()">
                            <label class="btn btn-outline-danger" for="elementFire">火</label>
                            
                            <input type="radio" class="btn-check" name="elementFilter" id="elementEarth" value="earth" onchange="filterCards()">
                            <label class="btn btn-outline-secondary" for="elementEarth">土</label>
                        </div>
                    </div>

                    <!-- 稀有度筛选 -->
                    <div class="mb-3">
                        <label class="form-label">稀有度</label>
                        <div class="btn-group-vertical w-100" role="group">
                            <input type="radio" class="btn-check" name="rarityFilter" id="rarityAll" value="" checked onchange="filterCards()">
                            <label class="btn btn-outline-primary" for="rarityAll">全部</label>
                            
                            <input type="radio" class="btn-check" name="rarityFilter" id="rarityCommon" value="common" onchange="filterCards()">
                            <label class="btn btn-outline-secondary" for="rarityCommon">普通</label>
                            
                            <input type="radio" class="btn-check" name="rarityFilter" id="rarityRare" value="rare" onchange="filterCards()">
                            <label class="btn btn-outline-primary" for="rarityRare">稀有</label>
                            
                            <input type="radio" class="btn-check" name="rarityFilter" id="rarityEpic" value="epic" onchange="filterCards()">
                            <label class="btn btn-outline-warning" for="rarityEpic">史诗</label>
                            
                            <input type="radio" class="btn-check" name="rarityFilter" id="rarityLegendary" value="legendary" onchange="filterCards()">
                            <label class="btn btn-outline-danger" for="rarityLegendary">传说</label>
                        </div>
                    </div>

                    <!-- 重置筛选 -->
                    <div class="d-grid">
                        <button class="btn btn-outline-secondary" onclick="resetFilters()">
                            <i class="fas fa-undo"></i> 重置筛选
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主内容区域 -->
        <div class="col-md-9">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center">
                        <a href="{% url 'home' %}" class="btn btn-outline-secondary btn-sm me-3" title="返回主页">
                            <i class="fas fa-arrow-left"></i> 返回主页
                        </a>
                        <h5 class="mb-0"><i class="fas fa-gem"></i> 我的卡牌收藏</h5>
                    </div>
                    <div>
                        <span class="badge bg-primary" id="ownedCount">拥有: 0</span>
                        <span class="badge bg-secondary" id="totalCount">总计: 0</span>
                    </div>
                </div>
                <div class="card-body">
                    <!-- 加载状态 -->
                    <div id="loadingState" class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2 text-muted">正在加载卡牌数据...</p>
                    </div>

                    <!-- 卡牌网格 -->
                    <div id="cardsGrid" class="row g-3" style="display: none;">
                        <!-- 卡牌将通过JavaScript动态加载 -->
                    </div>

                    <!-- 无结果状态 -->
                    <div id="noResults" class="text-center py-5" style="display: none;">
                        <i class="fas fa-search fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">没有找到匹配的卡牌</h5>
                        <p class="text-muted">请尝试调整筛选条件</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 基础变量
let allCards = [];
let ownedCards = [];

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadCardData();
});

// 加载卡牌数据
async function loadCardData() {
    try {
        // 获取筛选参数
        const filterParams = getFilterParams();
        
        // 构建API URL
        const apiUrl = buildApiUrl('/api/cards/', filterParams);
        
        // 并行加载筛选后的卡牌和用户拥有的卡牌
        const [allCardsResponse, ownedCardsResponse] = await Promise.all([
            fetch(apiUrl),
            fetch('/api/cards/owned/')
        ]);
        
        // 检查响应状态
        if (!allCardsResponse.ok || !ownedCardsResponse.ok) {
            throw new Error('API请求失败');
        }
        
        const allCardsData = await allCardsResponse.json();
        const ownedCardsData = await ownedCardsResponse.json();
        
        // 调试信息
        console.log('allCardsData:', allCardsData);
        console.log('ownedCardsData:', ownedCardsData);
        
        // 处理分页数据
        allCards = allCardsData.results || allCardsData;
        ownedCards = ownedCardsData.results || ownedCardsData;
        
        // 确保数据是数组格式
        if (!Array.isArray(allCards)) {
            console.error('allCards不是数组:', allCards);
            allCards = [];
        }
        
        if (!Array.isArray(ownedCards)) {
            console.error('ownedCards不是数组:', ownedCards);
            ownedCards = [];
        }
        
        // 创建拥有卡牌的映射
        const ownedCardMap = {};
        ownedCards.forEach(userCard => {
            if (userCard && userCard.card && userCard.card.id) {
                ownedCardMap[userCard.card.id] = userCard.quantity || 0;
            }
        });
        
        // 为所有卡牌添加拥有数量信息
        allCards.forEach(card => {
            card.owned_quantity = ownedCardMap[card.id] || 0;
            card.is_owned = card.owned_quantity > 0;
        });
        
        updateCounts();
        renderCards();
        
        // 隐藏加载状态，显示卡牌网格
        document.getElementById('loadingState').style.display = 'none';
        document.getElementById('cardsGrid').style.display = 'flex';
        
    } catch (error) {
        console.error('加载卡牌数据失败:', error);
        document.getElementById('loadingState').innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> 加载失败，请刷新页面重试
                <br><small>错误详情: ${error.message}</small>
            </div>
        `;
    }
}

// 更新计数
function updateCounts() {
    const ownedCount = allCards.filter(card => card.is_owned).length;
    const totalCount = allCards.length;
    
    document.getElementById('ownedCount').textContent = `拥有: ${ownedCount}`;
    document.getElementById('totalCount').textContent = `总计: ${totalCount}`;
}

// 渲染卡牌
function renderCards() {
    const showAll = document.getElementById('showAllCards').checked;
    const grid = document.getElementById('cardsGrid');
    const noResults = document.getElementById('noResults');
    
    // 前端筛选：是否显示未拥有的卡牌
    let cardsToRender = allCards;
    if (!showAll) {
        cardsToRender = allCards.filter(card => card.is_owned);
    }
    
    // 先清空网格内容
    grid.innerHTML = '';
    
    if (cardsToRender.length === 0) {
        // 没有结果时，隐藏网格，显示无结果提示
        grid.style.display = 'none';
        noResults.style.display = 'block';
        console.log('没有找到匹配的卡牌');
        return;
    }
    
    // 有结果时，显示网格，隐藏无结果提示
    grid.style.display = 'flex';
    grid.style.flexWrap = 'wrap';
    noResults.style.display = 'none';
    
    console.log(`渲染 ${cardsToRender.length} 张卡牌`);
    
    cardsToRender.forEach((card, index) => {
        const cardElement = createCardElement(card);
        grid.appendChild(cardElement);
        if (index < 3) {
            console.log(`卡牌 ${index + 1}: ${card.name}, 类名: ${cardElement.className}`);
        }
    });
}

// 创建卡牌元素
function createCardElement(card) {
    const col = document.createElement('div');
    col.className = 'col-lg-3 col-md-4 col-sm-6 col-12';
    
    const elementColors = {
        'metal': 'warning',
        'wood': 'success', 
        'water': 'info',
        'fire': 'danger',
        'earth': 'secondary'
    };
    
    const rarityColors = {
        'common': 'secondary',
        'rare': 'primary',
        'epic': 'warning',
        'legendary': 'danger'
    };
    
    const isOwned = card.is_owned;
    const opacity = isOwned ? '' : 'opacity-50';
    
    col.innerHTML = `
        <div class="card h-100 card-hover ${opacity}" onclick="showCardDetail(${card.id})">
            <div class="card-body p-3">
                <!-- 顶部信息栏 -->
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="badge bg-warning text-dark" style="font-size: 0.8rem;">
                        <i class="fas fa-star"></i> ${card.star_level || 1}
                    </span>
                    <span class="badge bg-${elementColors[card.element] || 'primary'}" style="font-size: 0.8rem;">
                        ${getElementName(card.element)}
                    </span>
                </div>
                
                <!-- 卡牌名称 -->
                <h6 class="card-title mb-2" style="font-size: 1rem; line-height: 1.3; font-weight: 600;">${card.name}</h6>
                
                <!-- 描述 -->
                <p class="card-text text-muted mb-3" style="font-size: 0.8rem; line-height: 1.3;">
                    ${card.description.substring(0, 40)}...
                </p>
                
                <!-- 底部信息栏 -->
                <div class="d-flex justify-content-between align-items-center">
                    <span class="badge bg-${rarityColors[card.rarity] || 'secondary'}" style="font-size: 0.75rem;">
                        ${getRarityName(card.rarity)}
                    </span>
                    <div class="d-flex align-items-center">
                        <small class="text-muted me-2" style="font-size: 0.8rem;">
                            <i class="fas fa-bolt"></i> ${card.attack_power}
                        </small>
                        ${isOwned ? `
                            <span class="badge bg-success" style="font-size: 0.7rem;">
                                x${card.owned_quantity}
                            </span>
                        ` : `
                            <span class="badge bg-secondary" style="font-size: 0.7rem;">
                                <i class="fas fa-lock"></i>
                            </span>
                        `}
                    </div>
                </div>
            </div>
        </div>
    `;
    
    return col;
}

// 获取属性名称
function getElementName(element) {
    const elementNames = {
        'metal': '金',
        'wood': '木',
        'water': '水',
        'fire': '火',
        'earth': '土'
    };
    return elementNames[element] || element;
}

// 获取稀有度名称
function getRarityName(rarity) {
    const rarityNames = {
        'common': '普通',
        'rare': '稀有',
        'epic': '史诗',
        'legendary': '传说'
    };
    return rarityNames[rarity] || rarity;
}

// 获取筛选参数
function getFilterParams() {
    const params = {};
    
    // 搜索参数
    const search = document.getElementById('searchInput').value.trim();
    if (search) {
        params.search = search;
    }
    
    // 星级筛选
    const starFilter = document.querySelector('input[name="starFilter"]:checked').value;
    if (starFilter) {
        params.star_level = starFilter;
    }
    
    // 属性筛选
    const elementFilter = document.querySelector('input[name="elementFilter"]:checked').value;
    if (elementFilter) {
        params.element = elementFilter;
    }
    
    // 稀有度筛选
    const rarityFilter = document.querySelector('input[name="rarityFilter"]:checked').value;
    if (rarityFilter) {
        params.rarity = rarityFilter;
    }
    
    return params;
}

// 构建API URL
function buildApiUrl(baseUrl, params) {
    const url = new URL(baseUrl, window.location.origin);
    Object.keys(params).forEach(key => {
        if (params[key]) {
            url.searchParams.append(key, params[key]);
        }
    });
    return url.toString();
}

// 切换显示全部卡牌
function toggleShowAll() {
    filterCards();
}

// 筛选卡牌
function filterCards() {
    const grid = document.getElementById('cardsGrid');
    const noResults = document.getElementById('noResults');
    
    // 立即清空之前的结果
    grid.innerHTML = '';
    grid.style.display = 'none';
    noResults.style.display = 'none';
    
    // 显示加载状态
    document.getElementById('loadingState').style.display = 'block';
    
    // 重新加载数据（使用后端筛选）
    loadCardData();
}

// 重置筛选
function resetFilters() {
    document.getElementById('showAllCards').checked = false;
    document.getElementById('searchInput').value = '';
    document.getElementById('starAll').checked = true;
    document.getElementById('elementAll').checked = true;
    document.getElementById('rarityAll').checked = true;
    
    filterCards();
}

// 显示卡牌详情（暂时显示简单信息）
function showCardDetail(cardId) {
    const card = allCards.find(c => c.id === cardId);
    if (!card) return;
    
    alert(`卡牌详情：\n名称：${card.name}\n星级：${card.star_level || 1}星\n属性：${getElementName(card.element)}\n攻击力：${card.attack_power}\n稀有度：${getRarityName(card.rarity)}\n描述：${card.description}`);
}
</script>

<style>
.card-hover {
    transition: transform 0.2s ease-in-out;
    cursor: pointer;
    border: 1px solid #dee2e6;
}

.card-hover:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.opacity-50 {
    opacity: 0.5;
}

.btn-check:checked + .btn {
    background-color: var(--bs-primary);
    border-color: var(--bs-primary);
    color: white;
}

/* 优化网格间距 */
#cardsGrid {
    margin: 0;
    display: flex !important;
    flex-wrap: wrap !important;
}

#cardsGrid > div {
    padding: 0 8px 16px 8px;
    flex: 0 0 auto;
}

/* 响应式调整 */
@media (max-width: 768px) {
    #cardsGrid > div {
        padding: 0 4px 12px 4px;
    }
}

/* 卡牌样式优化 */
.card {
    min-height: 200px;
    border-radius: 8px;
    width: 100%;
}

.card-body {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

/* 徽章样式优化 */
.badge {
    font-weight: 500;
}

/* 确保网格正确显示 */
.row.g-3 {
    --bs-gutter-x: 1rem;
    --bs-gutter-y: 1rem;
}

/* 强制Bootstrap网格工作 */
.col-lg-3 {
    flex: 0 0 25%;
    max-width: 25%;
}

.col-md-4 {
    flex: 0 0 33.333333%;
    max-width: 33.333333%;
}

.col-sm-6 {
    flex: 0 0 50%;
    max-width: 50%;
}

.col-12 {
    flex: 0 0 100%;
    max-width: 100%;
}

@media (min-width: 992px) {
    .col-lg-3 {
        flex: 0 0 25%;
        max-width: 25%;
    }
}

@media (min-width: 768px) and (max-width: 991.98px) {
    .col-md-4 {
        flex: 0 0 33.333333%;
        max-width: 33.333333%;
    }
}

@media (min-width: 576px) and (max-width: 767.98px) {
    .col-sm-6 {
        flex: 0 0 50%;
        max-width: 50%;
    }
}

@media (max-width: 575.98px) {
    .col-12 {
        flex: 0 0 100%;
        max-width: 100%;
    }
}
</style>
{% endblock %}